<?php

//error_reporting(E_ALL);
//就近 www.jiujin.me
global $_W, $_GPC;
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
if ($operation == 'display'){
    ca('authenticity.list.view');
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;
    $list = pdo_fetchall("SELECT b.*,a.createtime as create_time,a.lottery_id,a.id as rec_id FROM " . tablename('authenticity_lottery') . "as a LEFT JOIN " . tablename('hx_lottery_reply') . "as b on a.lottery_id=b.id WHERE a.uniacid = '{$_W['uniacid']}' ORDER BY a.id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
    foreach ($list as $k => $v) {
        $chanyu_num = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('hx_lottery_fans') . " WHERE reply_id = '{$v['id']}'");
        $zhongjiang_num = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('hx_lottery_award') . " WHERE reply_id = '{$v['id']}'");
        $list[$k]['chanyu_num'] = $chanyu_num;
        $list[$k]['zhongjiang_num'] = $zhongjiang_num;
        $list[$k]['create_time'] = date('Y-m-d H:i', $v['create_time']);
    }
    $total = pdo_fetchcolumn("SELECT * FROM " . tablename('authenticity_lottery') . " WHERE uniacid = '{$_W['uniacid']}' ORDER BY id DESC");
    $pager = pagination($total, $pindex, $psize);
}

if ($operation == 'post') {
    ca('authenticity.list.add');
    if (checksubmit('submit')) {
        if (empty($_GPC['lottery_id'])) {
            message('你没有选择抽奖活动！', $this->createWebUrl('authenticity/list', array('op' => 'post')), 'error');
        } else {
            $lottery_id = intval($_GPC['lottery_id']);
            $data = array(
                'uniacid' => $_W['uniacid'],
                'lottery_id' => $lottery_id,
                'createtime' => time()
            );
            pdo_insert('authenticity_lottery', $data);
            message('添加抽奖活动成功！', $this->createWebUrl('authenticity/list', array('op' => 'display')), 'success');
        }
    }
    $list = pdo_fetchall("SELECT * FROM " . tablename('hx_lottery_reply') . " WHERE uniacid = '{$_W['uniacid']}' order by id desc");
}
if ($operation == 'awardlist') {
    ca('authenticity.list.view');
    $reply_id = intval($_GPC['reply_id']);
    if (empty($reply_id)) {
        message('你没有选择抽奖活动！', $this->createWebUrl('authenticity/list'), 'error');
    }
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;
    $list = pdo_fetchall("SELECT * FROM " . tablename('hx_lottery_award') . " WHERE reply_id = '{$reply_id}' ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
    foreach ($list as $k => $v) {
        $record = pdo_fetch("SELECT * FROM " . tablename('hx_lottery_fans') . " WHERE reply_id = '{$reply_id}' and uid='{$v['uid']}'");
        $list[$k]['qid'] = $record['qid'];
    }
    $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('hx_lottery_award') . " WHERE reply_id = '{$reply_id}'");
    $pager = pagination($total, $pindex, $psize);
}
if ($operation == "detail") {
    ca('authenticity.list.view');
    if (empty($_GPC['uid'])) {
        message('操作错误！', $this->createWebUrl('authenticity/list'), 'error');
    }
    $data = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_member') . " WHERE uid = '{$_GPC['uid']}' and uniacid = '{$_W['uniacid']}'");
}

if ($operation == 'qrcode') {
    ca('authenticity.list.edit');
    $id = $_GPC['id'];
    $time = time();
    if (checksubmit('submit')) {
        $production_time=strtotime($_GPC['production_time']);//生产日期时间硕
        $jumpurl = 'http://wx.lanxuevip.com/app/index.php?i=5&c=entry&do=authenticity&m=ewei_shop&id=' . $id .'&company='.$_GPC['company'].'&brandname='.$_GPC['brandname'].'&goodsname='.$_GPC['goodsname'].'&production_time='.$production_time;
        $path = IA_ROOT . "/addons/ewei_shop/data/authenticity/" . $_W['uniacid'] . "/";
        if (!is_dir($path)) {
            load()->func('file');
            mkdirs($path);
        }
        $barcode = array(
            'expire_seconds' => '',
            'action_name' => '',
            'action_info' => array(
            'scene' => array(),
            ),
        );
        $acid = intval($_W['acid']);
        $uniacccount = WeAccount::create($acid);

        if ($_GPC['id'] == '') {
            message('抱歉，没有该抽奖活动！', $this->createWebUrl('authenticity/list', array('op' => 'display')), 'error');
        }
        if(empty($_GPC['company']) && empty($_GPC['brandname']) && empty($_GPC['goodsname'])){
            message('抱歉，请将信息填写完整！', $this->createWebUrl('authenticity/list', array('op'=>'qrcode', 'id' =>$id)), 'error');
        }
        if($production_time == FALSE){
            message('抱歉，请正确的填写生产日期！', $this->createWebUrl('authenticity/list', array('op'=>'qrcode', 'id' =>$id)), 'error');
        }
        //只生成一遍即可
        //ims_rule
        $rule = array(
            'uniacid' => $_W['uniacid'],
            'name' => $_GPC['name'],
            'module' => 'news',
            'displayorder' => 0,
            'status' => 1
        );
        pdo_insert('rule', $rule);
        $rid = pdo_insertid();
        //ims_rule_keyword
        $rulekeyword = array(
            'rid' => $rid,
            'uniacid' => $_W['uniacid'],
            'module' => 'news',
            'content' => $_GPC['keyword'],
            'type' => 1,
            'displayorder' => 0,
            'status' => 1
        );
        pdo_insert('rule_keyword', $rulekeyword);
        //ims_news_reply
        $newsreply = array(
            'rid' => $rid,
            'parentid' => 0,
            'title' => $_GPC['title'],
            'description' => $_GPC['description'],
            'thumb' => $_GPC['thumb'],
            'content' => '',
            'url' => $jumpurl,
            'displayorder' => 0,
            'incontent' => 1,
            'author' => '',
            'createtime' => TIMESTAMP
        );
        pdo_insert('news_reply', $newsreply);
        require IA_ROOT . '/framework/library/qrcode/phpqrcodecolor.php';
        //批量加入数据库
        $number = intval($_GPC['number']);
        for ($i = 1; $i <= $number; $i++) {
            //ims_qrcode
            $jumpurl = 'http://wx.lanxuevip.com/app/index.php?i=5&c=entry&do=authenticity&m=ewei_shop&id=' . $id .'&company='.$_GPC['company'].'&brandname='.$_GPC['brandname'].'&goodsname='.$_GPC['goodsname'].'&production_time='.$production_time;
            $qrctype = intval($_GPC['qrc-model']);
            if ($qrctype == 1) {
                $qrcid = pdo_fetchcolumn("SELECT qrcid FROM " . tablename('qrcode') . " WHERE acid = :acid AND model <> '2' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
                $barcode['action_info']['scene']['scene_id'] = !empty($qrcid) ? ($qrcid + 1) : 100001;
                $during = strtotime($_GPC['time']['end']) - strtotime($_GPC['time']['start']);
                $barcode['expire_seconds'] = intval($during);
                $barcode['action_name'] = 'QR_SCENE';
                $result = $uniacccount->barCodeCreateDisposable($barcode);
            } else if ($qrctype == 2) {
                $scene_str = trim($_GPC['scene_str']);
                if (!empty($scene_str)) {
                    $barcode['action_info']['scene']['scene_str'] = $scene_str;
                    $barcode['action_name'] = 'QR_LIMIT_STR_SCENE';
                } else {
                    $qrcid = pdo_fetchcolumn("SELECT qrcid FROM " . tablename('qrcode') . " WHERE acid = :acid AND model = '2' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
                    $barcode['action_info']['scene']['scene_id'] = !empty($qrcid) ? ($qrcid + 1) : 1;
                    if ($barcode['action_info']['scene']['scene_id'] > 100000) {
                        message('抱歉，永久二维码已经生成最大数量，请先删除一些。');
                    }
                    $barcode['action_name'] = 'QR_LIMIT_SCENE';
                }
                $result = $uniacccount->barCodeCreateFixed($barcode);
            } else if ($qrctype == 3) {
                $qrcid = pdo_fetchcolumn("SELECT qrcid FROM " . tablename('qrcode') . " WHERE acid = :acid AND model <> '2' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
                $barcode['action_info']['scene']['scene_id'] = !empty($qrcid) ? ($qrcid + 1) : 100001;
                $file =$barcode['action_info']['scene']['scene_id'] . '.png';
                $qr_file = $path . $file;
                $during =604800;
                $color = 0;
                $jumpurl = $jumpurl . '&qid=' . $barcode['action_info']['scene']['scene_id'];
                $barcode['expire_seconds'] = intval($during);
                $barcode['action_name'] = 'QR_SCENE';
                QRcode::png($jumpurl, $qr_file, 'L', 8, 4, false, $color);
            } else {
                message('抱歉，此公众号暂不支持您请求的二维码类型！');
            }
            if ($qrctype == 3){
                    $insert = array(
                        'uniacid' => $_W['uniacid'],
                        'acid' => $acid,
                        'qrcid' => $barcode['action_info']['scene']['scene_id'],
                        'scene_str' =>'',
                        'keyword' => $_GPC['keyword'],
                        'name' => $_GPC['title'],
                        'model' => 0,
                        'ticket' => $result['ticket'],
                        'url' => $jumpurl,
                        'expire' => 0,
                        'createtime' => TIMESTAMP,
                        'status' => '1',
                        'type' => 'scene',
                        'special' => '1'  //代表着只能扫一次
                    );
                    pdo_insert('qrcode', $insert);
                //保存图片到data里
                //$img = file_get_contents('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$result['ticket']); 
                $img = file_get_contents($_W['siteroot'] . 'addons/ewei_shop/data/authenticity/' . $_W['uniacid'] . '/' . $file);
                file_put_contents($path . $barcode['action_info']['scene']['scene_id'] . '.png', $img);
            }else {
                if (!is_error($result)) {
                    $insert = array(
                        'uniacid' => $_W['uniacid'],
                        'acid' => $acid,
                        'qrcid' => $barcode['action_info']['scene']['scene_id'],
                        'scene_str' => $barcode['action_info']['scene']['scene_str'],
                        'keyword' => $_GPC['keyword'],
                        'name' => $_GPC['title'],
                        'model' => $_GPC['qrc-model'],
                        'ticket' => $result['ticket'],
                        'url' => $result['url'],
                        'expire' => $result['expire_seconds'],
                        'createtime' => TIMESTAMP,
                        'status' => '1',
                        'type' => 'scene',
                        'special' => '1'  //代表着只能扫一次
                    );
                    pdo_insert('qrcode', $insert);
                } else {
                    message("公众平台返回接口错误. <br />错误代码为: {$result['errorcode']} <br />错误信息为: {$result['message']}");
                }
                //保存图片到data里
                $img = file_get_contents('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $result['ticket']);
                //$img = file_get_contents($_W['siteroot'] . 'addons/ewei_shop/data/batch/' . $_W['uniacid'] . '/' . $file);
                file_put_contents($path . $barcode['action_info']['scene']['scene_id'] . '.png', $img);
            }
        }

        //压缩
        $zip = new ZipArchive();
        if ($zip->open(IA_ROOT . '/addons/ewei_shop/data/authenticity/' . $_W['uniacid'] . '/' . $time . '.rar', ZipArchive::OVERWRITE) === TRUE) {
            //批量压缩
            for ($i = 1; $i <= $number; $i++) {
                $bianhao=$barcode['action_info']['scene']['scene_id']-$number+$i;
                $zip->addFile(IA_ROOT . '/addons/ewei_shop/data/authenticity/' . $_W['uniacid'] . '/' . $bianhao . '.png');
            }
        }
        $zip->close();
        //ims_ewei_shop_download
        $downld = array(
            'name' => $time . '.rar',
            'createtime' => TIMESTAMP,
            'uniacid' => $_W['uniacid'],
            'type' =>7
        );
        pdo_insert('ewei_shop_download', $downld);
        message('批量生成二维码成功！', $this->createWebUrl('authenticity/list', array('op' => 'display')), 'success');
    }
}
if ($operation == 'download') {
    ca('authenticity.list.export');
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;
    $list = pdo_fetchall("SELECT * FROM " . tablename('ewei_shop_download') . " WHERE uniacid = '{$_W['uniacid']}' AND type = 7 ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
    foreach ($list as $key => $value) {
        $list[$key]['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
        $list[$key]['downlink'] = 'http://wx.lanxuevip.com/addons/ewei_shop/data/authenticity/' . $_W['uniacid'] . '/' . $value['name'];
        $list[$key]['deletelink'] = $this->createWebUrl('authenticity/list', array('op' => 'downloaddelete', 'id' => $value['id']));
    }
    $total = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('ewei_shop_download') . " WHERE uniacid = '{$_W['uniacid']}' AND type = 7 ORDER BY id DESC");
    $pager = pagination($total, $pindex, $psize);
}
if ($operation == 'downloaddelete') {
    ca('authenticity.list.delete');
    $id = intval($_GPC['id']);
    $data = pdo_fetch("SELECT id,name FROM " . tablename('ewei_shop_download') . " WHERE id = '{$id}' AND type = 7 AND uniacid=" . $_W['uniacid'] . "");
    if (empty($data)) {
        message('抱歉，该压缩包不存在或是已经被删除！', $this->createWebUrl('authenticity/list', array('op' => 'display')), 'error');
    }
    pdo_delete('ewei_shop_download', array('id' => $id));
    unlink(IA_ROOT . '/addons/ewei_shop/data/authenticity/' . $_W['uniacid'] . '/' . $data['name']);
    message('压缩包删除成功！', $this->createWebUrl('authenticity/list', array('op' => 'display')), 'success');
}
if($operation == 'information'){
    ca('authenticity.list.view');
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;
    $condition="";
    if (!empty($_GPC['realname'])) {
        $_GPC['realname'] = trim($_GPC['realname']);
        $condition .= ' and ( m.weixin like :realname or m.realname like :realname or m.mobile like :realname or m.nickname like :realname)';
        $params[':realname'] = "%{$_GPC['realname']}%";
    }
    if(!empty($_GPC['qid'])){
        $_GPC['qid'] = trim($_GPC['qid']);
        $condition .=' and a.qid=:qid';
        $params[':qid'] =$_GPC['qid'];
    }
    if(!empty($_GPC['company'])){
        $_GPC['company'] = trim($_GPC['company']);
        $condition .=' and a.company=:company';
        $params[':company'] =$_GPC['company'];
    }
    if(!empty($_GPC['brandname'])){
        $_GPC['brandname'] = trim($_GPC['brandname']);
        $condition .=' and a.brandname=:brandname';
        $params[':brandname'] =$_GPC['brandname'];
    }
    if(!empty($_GPC['goodsname'])){
        $_GPC['goodsname'] = trim($_GPC['goodsname']);
        $condition .=' and a.goodsname=:goodsname';
        $params[':goodsname'] =$_GPC['goodsname'];
    }
    $record=pdo_fetchall('SELECT a.*,m.avatar,m.nickname FROM ' .tablename('authenticity_information')." AS a LEFT JOIN ".tablename('ewei_shop_member')."AS m ON a.openid=m.openid where a.uniacid='{$_W['uniacid']}' $condition order by a.id desc limit  ". ($pindex - 1) * $psize . ',' . $psize,$params);
    $total = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('authenticity_information') . " WHERE uniacid = '{$_W['uniacid']}' ORDER BY id DESC");
    $pager = pagination($total, $pindex, $psize);
    //导出列表
    if ($_GPC['export'] == 1) {
                ca('authenticity.list.export');
                $record=pdo_fetchall('SELECT a.*,m.avatar,m.nickname FROM ' .tablename('authenticity_information')." AS a LEFT JOIN ".tablename('ewei_shop_member')."AS m ON a.openid=m.openid where a.uniacid='{$_W['uniacid']}' $condition order by a.id desc ",$params);
                foreach($record as $k=>$v){
                    if($v['production_time']){
                    $record[$k]['production_time']=date('Y-m-d H:i',$v['production_time']);
                    }else{
                    $record[$k]['production_time']=""; 
                    }
                    if($v['createtime']){
                    $record[$k]['createtime']=date('Y-m-d H:i',$v['createtime']);
                    }else{
                    $record[$k]['createtime']="";    
                    }
                    $record[$k]['addresses']=$v['province'].''.$v['city'].''.$v['area'].''.$v['address'];
                }
                $columns = array(
                    array('title' => '编号QID', 'field' => 'qid', 'width' => 12),
                    array('title' => '昵称', 'field' => 'nickname', 'width' => 12), 
                    array('title' => '抽奖活动ID', 'field' => 'auth_id', 'width' => 12),  
                    array('title' => '公司名称', 'field' => 'company', 'width' => 12),
                    array('title' => '产品品牌', 'field' => 'brandname', 'width' => 12),
                    array('title' => '产品名称', 'field' => 'goodsname', 'width' => 12),
                    array('title' => "生产日期", 'field' => 'production_time', 'width' => 24),
                    array('title' => '提交时间', 'field' => 'createtime', 'width' => 12),
                    array('title' => '门店地址', 'field' => 'addresses', 'width' => 12),
                    array('title' => '门店名称', 'field' => 'information', 'width' => 12),
               );
                m('excel')->export($record, array("title" => "门店信息导出" . date('Y-m-d-H-i', time()), "columns" => $columns));
    }
}
load()->func('tpl');
include $this->template('web/authenticity/list');
